﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using SessionHunter.Messages;

namespace SessionHunter.ViewModel
{
    /// <summary>
    /// If we want the view model to react to messages, this is a base class that can be used to give it a standard
    /// structure.  There is a message class, with an enum that has a strongly typed set of messages instead
    /// of a string value.
    /// </summary>
    /// <typeparam name="MessageClass">The type of the essage class.</typeparam>
    /// <typeparam name="MessageActionType">The type of the essage action type.</typeparam>
    public abstract class ViewModelBaseWithNotifications<MessageClass, MessageActionType> : ViewModelBase
        where MessageClass : MessageClassBase<MessageActionType>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelBaseWithNotifications&lt;MessageClass, MessageActionType&gt;"/> class.
        /// </summary>
        protected ViewModelBaseWithNotifications()
        {
            Messenger.Default.Register<MessageClass>(this, NotificationMessageReceived);
        }

        /// <summary>
        /// When a message is received, it is processed by this method
        /// </summary>
        /// <param name="msg">The message, with the associated action</param>
        protected abstract void NotificationMessageReceived(MessageClass msg);

        /// <summary>
        /// Unregisters this instance from the Messenger class.
        /// <para>To cleanup additional resources, override this method, clean
        /// up and then call base.Cleanup().</para>
        /// </summary>
        public override void Cleanup()
        {
            Messenger.Default.Unregister<MessageClass>(this);
            base.Cleanup();
        }
    }
}
